<template>
	<view class="customer-form">
		<!-- 导航栏 -->

		<scroll-view class="form-content" scroll-y="true">
			<!-- 基础信息 -->
			<view class="form-section">
				<view class="form-grid">
					<!-- 姓名 -->
					<view class="form-item">
						<view class="label-row">
							<text class="item-label">姓名</text>
							<text class="item-required">*</text>
						</view>
						<uni-easyinput class="item-input" type="text" placeholder="请输入姓名"
							v-model="formData.customerName" @blur="validateField('customerName')"
							:inputBorder="false" />
						<text class="error-msg" v-if="errors.name">{{ errors.name }}</text>
					</view>
					<view class="form-item">
						<view class="label-row">
							<text class="item-label">手机号码</text>
							<!-- <text class="item-required">*</text> -->
						</view>
						<uni-easyinput class="item-input" type="number" placeholder="请输入手机号码" v-model="formData.phone"
							:disabled="!!formData._id || !!phone" @blur="validateField('phone')" :inputBorder="false" />
						<text class="error-msg" v-if="errors.phone">{{ errors.phone }}</text>
					</view>

					<!-- 性别 -->
					<view class="form-item">
						<text class="item-label label-row">性别</text>
						<view class="radio-group">
							<view class="radio-option" :class="{ active: formData.gender === 'male' }"
								@click="formData.gender = 'male'">
								<view class="radio-dot"></view>
								<text class="radio-text">男</text>
							</view>
							<view class="radio-option" :class="{ active: formData.gender === 'female' }"
								@click="formData.gender = 'female'">
								<view class="radio-dot"></view>
								<text class="radio-text">女</text>
							</view>
						</view>
					</view>
					
						<view class="form-item">
							<text class="item-label label-row">客户来源</text>
							<picker class="item-picker" mode="selector" :range="$sourceType"
								@change="onFormOptions($event,'formType',$sourceType)" range-key="text">
								<view class="picker-content">
									<text class="picker-text"
										:class="{'active':formData.formType}">{{ getText($sourceType,formData.formType) || '请选择' }}</text>
									<text class="picker-arrow">▼</text>
								</view>
							</picker>
						</view>
					<template v-if="$userInfo.role != 6">
					<view class="form-item">
						<view class="label-row">
							<text class="item-label">身份证号</text>
							<!-- <text class="item-required">*</text> -->
						</view>
						<uni-easyinput class="item-input" type="idcard" placeholder="请输入身份证号码" v-model="formData.idCard"
							@blur="validateField('idCard')" :inputBorder="false" />
						<text class="error-msg" v-if="errors.idCard">{{ errors.idCard }}</text>
					</view>

					<!-- 职业 -->
					<view class="form-item">
						<text class="item-label">职业</text>
						<picker class="item-picker" mode="selector" :range="jobOptions" @change="onJobChange">
							<view class="picker-content">
								<text class="picker-text">{{ formData.job || '请选择' }}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>

					<!-- 微信号 -->
					<view class="form-item">
						<text class="item-label">微信号</text>
						<uni-easyinput class="item-input" type="text" placeholder="请输入微信号" v-model="formData.wechat"
							:inputBorder="false" />
					</view>

					<view class="form-item">
						<text class="item-label">居住区域</text>
						<uni-data-select></uni-data-select>
						<uni-easyinput class="item-input" type="text" placeholder="请输入居住地址" v-model="formData.address"
							:inputBorder="false" />
					</view>
					</template>
				</view>
			</view>
			<template v-if="$userInfo.role != 6">
			<!-- 家庭信息 -->
			<view class="form-section">
				<view class="form-grid">
					<!-- 婚姻状况 -->
					<view class="form-item">
						<text class="item-label">婚姻状况</text>
						<picker class="item-picker" mode="selector" :range="marriageOptions" @change="onMarriageChange">
							<view class="picker-content">
								<text class="picker-text">{{ formData.marriage || '请选择' }}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>

					<!-- 有无小孩 -->
					<template v-if="showChildrenField">
						<view class="form-item">
							<text class="item-label">是否有小孩</text>
							<view class="radio-group">
								<view class="radio-option" :class="{ active: formData.hasChildren === 'yes' }"
									@click="formData.hasChildren = 'yes'">
									<view class="radio-dot"></view>
									<text class="radio-text">是</text>
								</view>
								<view class="radio-option" :class="{ active: formData.hasChildren === 'no' }"
									@click="formData.hasChildren = 'no'">
									<view class="radio-dot"></view>
									<text class="radio-text">否</text>
								</view>
							</view>
						</view>

						<!-- 孩子数量 -->
						<view class="form-item" v-if="formData.hasChildren === 'yes'">
							<text class="item-label">孩子数量</text>
							<picker class="item-picker" mode="selector" :range="childrenCountOptions"
								@change="onChildrenCountChange">
								<view class="picker-content">
									<text class="picker-text">{{ formData.childrenCount || '请选择' }}</text>
									<text class="picker-arrow">▼</text>
								</view>
							</picker>
						</view>

						<!-- 收入 -->
					</template>

					<view class="form-item">
						<text class="item-label">收入</text>
						<picker class="item-picker" mode="selector" :range="incomeOptions" @change="onIncomeChange">
							<view class="picker-content">
								<text class="picker-text">{{ formData.income || '请选择' }}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>


				</view>
			</view>
			</template>
			<!-- 购房需求 -->
			<view class="form-section">
				<!-- <view class="form-grid">
					<view class="form-item">
						<text class="item-label">意向户型</text>
						<uni-data-checkbox v-model="formData.houseType" :localdata="houseTypeOptions" mode="tag"
							multiple selectedColor="#FF9500" @change="onHouseTypeChange" />
					</view>

					<view class="form-item">
						<text class="item-label">预算范围</text>
						<picker class="item-picker" mode="selector" :range="budgetRanges" @change="onBudgetChange">
							<view class="picker-content">
								<text class="picker-text">{{ formData.budget || '请选择' }}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>
				</view> -->

				<!-- 购房目的 - 多选 -->
				<!-- 	<view class="form-item full-width">
					<text class="item-label">购房目的</text>
					<uni-data-checkbox v-model="formData.purpose" :localdata="purchasePurposeOptions" mode="tag"
						multiple selectedColor="#FF9500" @change="onPurposeChange" />
				</view> -->

				<view class="form-item">
					<text class="item-label">备注</text>
					<uni-easyinput type="textarea" v-model="formData.remark" autoHeight></uni-easyinput>
				</view>

				<!-- <view class="form-item" v-if="$userInfo.role == 4 || $userInfo.role == 5" style="margin-top: 20rpx;">
					<view class="label-row">
						<text class="item-label">看房日期</text>
						<text class="item-required">*</text>
					</view>
					<picker class="time-picker" mode="date" :value="formData.schedule_time" @change="onDateChange">
						<view class="picker-content">
							<text class="picker-text">{{ formData.schedule_time || '选择预计看房日期' }}</text>
							<text class="picker-arrow">▼</text>
						</view>
					</picker>
				</view> -->


			</view>

			<view class="form-section" v-if="formData._id && formData.middObj">
				<view class="form-grid">
					<view class="section-title">
						中介信息
						<template
							v-if="$userInfo.role!=4 && formData.middObj && formData.middObj.zhongjieYWYName">【{{formData.middlemanName}}】</template>
					</view>

					<view class="form-item">
						<text class="item-label">业务员姓名</text>
						<uni-easyinput class="item-input" type="text" v-model="formData.middObj.zhongjieYWYName"
							:disabled="$userInfo.role !=4" :inputBorder="false" />
					</view>
					<view class="form-item">
						<text class="item-label">业务员电话</text>
						<uni-easyinput class="item-input" type="text" v-model="formData.middObj.zhongjieYWYPhone"
							:disabled="$userInfo.role !=4" :inputBorder="false" />
					</view>
					<view class="form-item">
						<text class="item-label">业务员门市</text>
						<uni-easyinput class="item-input" type="text" v-model="formData.middObj.zhongjieYWYShop"
							:disabled="$userInfo.role !=4" :inputBorder="false" />
					</view>
				</view>
			</view>



			<!-- 提交按钮 -->
			<view class="action-section">
				<button class="submit-btn" @tap="submitForm" :disabled="isSubmitting">
					<text class="btn-text">{{ isSubmitting ? '提交中...' : '确认提交' }}</text>
				</button>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	// 添加中介  业务员 名字 电话 门店

	export default {
		data() {
			return {
				formData: {
					name: '',
					gender: 'male',
					idCard: '',
					phone: '',
					wechat: '',
					job: '',
					marriage: '',
					income: '',
					hasChildren: '',
					childrenCount: '',
					houseType: [], // 改为数组存储多个选项
					budget: '',
					remark: '',
					purpose: [],
					address: '', // 改为数组存储多个选项
					schedule_time: '',
					_id: '',
					middObj: {},
					sourceType:''
				},
				errors: {
					name: '',
					idCard: '',
					phone: ''
				},
				isSubmitting: false,
				houseTypeOptions: [{
						value: '一室一厅',
						text: '一室一厅'
					},
					{
						value: '两室一厅',
						text: '两室一厅'
					},
					{
						value: '两室两厅',
						text: '两室两厅'
					},
					{
						value: '三室一厅',
						text: '三室一厅'
					},
					{
						value: '三室两厅',
						text: '三室两厅'
					},
					{
						value: '四室两厅',
						text: '四室两厅'
					},
					{
						value: '复式',
						text: '复式'
					},
					{
						value: '别墅',
						text: '别墅'
					}
				],
				budgetRanges: [
					'100万以下',
					'100-200万',
					'200-300万',
					'300-500万',
					'500-800万',
					'800万以上'
				],
				purchasePurposeOptions: [{
						value: 'living',
						text: '自住',
						icon: '🏠'
					},
					{
						value: 'investment',
						text: '投资',
						icon: '📈'
					},
					{
						value: 'school',
						text: '学区',
						icon: '🎓'
					},
					{
						value: 'marriage',
						text: '婚房',
						icon: '💍'
					},
					{
						value: 'upgrade',
						text: '改善',
						icon: '✨'
					}
				],
				formOptions:[
					'朋友介绍',
					'广告',
				],
				marriageOptions: [
					'未婚',
					'已婚',
					'离异',
					'丧偶'
				],
				incomeOptions: [
					'10-20万',
					'20-30万',
					'30-50万',
					'50万以上'
				],
				childrenCountOptions: [
					'1个',
					'2个',
					'3个',
					'4个及以上'
				],
				jobOptions: [
					'私企职员',
					'国企职员',
					'事业单位',
					'个体经营者',
					'自由职业者',
					'学生',
					'教师',
					'医生',
					'工程师',
					'设计师',
					'销售人员',
					'管理人员',
					'其他'
				],
				eventType: '',
				phone: '',
			}
		},
		onLoad(query) {
			uni.setNavigationBarTitle({
				title: '添加客户'
			})
			console.log('query', query)
			// 前台第一次录入
			if (query.type == 2) {
				this.eventType = 2
			} else if (query.isEditor) {
				uni.setNavigationBarTitle({
					title: '编辑客户'
				})
				return this.initData()
			}
			let phone = query.phone
			let isPhone = !/^1[3-9]\d{9}$/.test(phone)
			if (phone) {
				this.formData.phone = phone
				this.phone = phone
			}
		},

		computed: {
			showChildrenField() {
				return this.formData.marriage !== '未婚' && this.formData.marriage;
			}
		},
		methods: {
			getText(arr, val) {
				let res = ''
				if (Array.isArray(val)) {
					val.map(item => {
						arr.map(one => {
							if (one.value == item) {
								res = res + ' ' + one.text
							}
						})
					})
				} else {
					for (var key in arr) {
						const item = arr[key]
						if (item.value == val) {
							res = item.text
							break;
						}
					}
				}
				return res
			},
			initData() {
				let customer = uni.getStorageSync('editorCustomer')
				if (customer.childrenCount) {
					customer.hasChildren = 'yes'
				} else {
					customer.hasChildren = 'no'
				}
				this.formData = {
					...customer
				}
			},

			validateField(field) {
				const value = this.formData[field]
				switch (field) {
					case 'customerName':
						this.errors.name = !value ? '请输入姓名' : value.length < 2 ? '姓名至少2个字符' : ''
						break
					case 'idCard':
						this.errors.idCard = !value ? '请输入身份证号' : !/^\d{17}[\dXx]$/.test(value) ? '身份证格式不正确' : ''
						break
					case 'phone':
						this.errors.phone = !value ? '请输入手机号' : !/^1[3-9]\d{9}$/.test(value) ? '手机号格式不正确' : ''
						break
				}
			},

			onHouseTypeChange(e) {
				// 多选模式下，e.detail.value 是选中的选项数组
				console.log('选中的户型：', this.formData.houseType)
			},

			onBudgetChange(e) {
				const index = e.detail.value
				this.formData.budget = this.budgetRanges[index]
			},

			onPurposeChange(e) {
				// 多选模式下，e.detail.value 是选中的选项数组
				console.log('选中的购房目的：', this.formData.purpose)
			},

			onMarriageChange(e) {
				const index = e.detail.value
				this.formData.marriage = this.marriageOptions[index]
				// 重置相关的子字段
				this.formData.hasChildren = ''
				this.formData.childrenCount = ''
			},

			onIncomeChange(e) {
				const index = e.detail.value
				this.formData.income = this.incomeOptions[index]
			},

			onChildrenCountChange(e) {
				const index = e.detail.value
				this.formData.childrenCount = this.childrenCountOptions[index]
			},

			onJobChange(e) {
				const index = e.detail.value
				this.formData.job = this.jobOptions[index]
			},
			onFormOptions(e, type, list) {
				this.formData[type] = list[e.detail.value].value
			
				console.log('this.formData[type]', this.formData[type])
				this.$forceUpdate()
			},
			saveDraft() {
				uni.setStorageSync('customerDraft', this.formData)
				uni.showToast({
					title: '已保存草稿',
					icon: 'success'
				})
			},

			async submitForm() {
				this.validateField('customerName')
				// this.validateField('idCard')
				this.validateField('phone')

				if (this.errors.consultantName || this.errors.phone) {
					return uni.showToast({
						title: '请完善必填信息',
						icon: 'none'
					})
				}

				this.isSubmitting = true
				try {

					let role = this.$userInfo.role



					let postData = {
						...this.formData
					}
					// 中介录入
					if (role == 4 || role == 5) {
						postData.zhongjieId = this.$userInfo._id
						postData.zhongjieName = this.$userInfo.agency
						postData.typeMap = 2
					} else {
						postData.schedule_time = this.$formatYear(new Date())
					}
					// 编辑时不改变isRegistration
					if (!this.formData._id) {
						postData.isRegistration = 0
					}

					// to do 置业顾问录入的客户 已要到访

					const res = await this.$cloudOBjAjax('suuny-custom', 'addCustomer', {
						...postData
					})

					if (role != 6) {
						this.$simpleToast('添加成功')
						this.$back()
						// let curTime = this.$formatYear(new Date())
						// let schedule_time = postData.schedule_time
						return

					} else {
						uni.redirectTo({
							url: "/pages/customer/fenpei?id=" + res.id
						})
					}






					console.log(res)
					// 分配销售人员
					// if(this.eventType == 2 && res.id){
					// 	console.log('1111')
					// 	uni.redirectTo({
					// 		url:"/pages/customer/fenpei?id=" +res.id
					// 	})
					// }

				} catch (error) {

					console.log(error)

					uni.showToast({
						title: error.errMsg,
						icon: 'none'
					})
				} finally {
					this.isSubmitting = false
				}
			},
			// 日期选择
			onDateChange(e) {
				this.formData.schedule_time = e.detail.value
			},
		}
	}
</script>

<style scoped lang="scss">
	.customer-form {
		min-height: 100%;
		background: #f8f9fa;
		overflow-y: auto;
	}


	/* 表单内容 */
	.form-content {
		padding: 30rpx;
		padding-bottom: 40rpx;
		box-sizing: border-box;
	}

	/* 表单区域 */
	.form-section {
		background: white;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
	}

	/* 表单网格布局 */
	.form-grid {
		display: grid;
		gap: 20rpx;
	}

	.form-item {
		display: flex;
		flex-direction: column;
	}


	.gender-item {
		margin-bottom: 40rpx;
	}

	.label-row {
		display: flex;
		align-items: center;
		// margin-bottom: 16rpx;
	}

	.item-label {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
		margin-bottom: 20rpx;
	}

	.item-required {
		color: #ff4757;
		margin-left: 4rpx;
		font-size: 24rpx;
	}

	.error-msg {
		color: #ff4757;
		font-size: 24rpx;
		margin-top: 8rpx;
	}

	/* 输入框样式 */
	::v-deep .uni-easyinput__content {
		border: 2rpx solid #e0e0e0 !important;
		border-radius: 12rpx !important;
		background: #fafafa !important;
		transition: all 0.3s;
	}

	::v-deep .uni-easyinput__content:focus-within {
		border-color: #FF9500 !important;
		background: white !important;
		box-shadow: 0 0 0 4rpx rgba(255, 149, 0, 0.1) !important;
	}

	/* 单选组样式 */
	.radio-group {
		display: flex;
		gap: 20rpx;
	}

	.radio-option {
		display: flex;
		align-items: center;
		padding: 16rpx 24rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 12rpx;
		background: #fafafa;
		transition: all 0.3s;
	}

	.radio-option.active {
		border-color: #FF9500;
		background: #fffaf0;
	}

	.radio-dot {
		width: 24rpx;
		height: 24rpx;
		border: 2rpx solid #ccc;
		border-radius: 50%;
		margin-right: 12rpx;
		position: relative;
	}

	.radio-option.active .radio-dot {
		border-color: #FF9500;
		background: #FF9500;
	}

	_RADIO_OPTION_ACTIVE .radio-dot::after {
		content: '';
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 12rpx;
		height: 12rpx;
		background: white;
		border-radius: 50%;
	}

	.radio-text {
		font-size: 26rpx;
		color: #333;
	}

	/* 选择器样式 */
	.picker-content {
		border: 2rpx solid #e0e0e0;
		border-radius: 12rpx;
		padding: 20rpx 24rpx;
		background: #fafafa;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.picker-text {
		font-size: 28rpx;
		color: #333;
	}

	.picker-text:placeholder {
		color: #999;
	}

	.picker-arrow {
		color: #999;
		font-size: 24rpx;
	}

	/* 购房目的网格 */
	.purpose-grid {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 20rpx;
		margin-top: 20rpx;
	}

	.purpose-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 24rpx 16rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 12rpx;
		background: #fafafa;
		transition: all 0.3s;
	}

	.purpose-item.active {
		border-color: #FF9500;
		background: #fffaf0;
		transform: translateY(-2rpx);
	}

	.purpose-icon {
		font-size: 40rpx;
		margin-bottom: 12rpx;
	}

	.purpose-text {
		font-size: 24rpx;
		color: #333;
	}

	/* 提交按钮 */
	.action-section {
		padding: 40rpx 0;
	}

	.submit-btn {
		background: #FF9500;
		color: white;
		border: none;
		border-radius: 12rpx;
		font-size: 30rpx;
		font-weight: 600;
		box-shadow: 0 4rpx 16rpx rgba(255, 149, 0, 0.3);
		transition: all 0.3s;
		line-height: 80rpx;
		height: 80rpx;
	}

	.submit-btn:active {
		transform: translateY(2rpx);
		box-shadow: 0 2rpx 8rpx rgba(255, 149, 0, 0.3);
	}

	.submit-btn:disabled {
		opacity: 0.6;
	}

	.btn-text {
		font-size: 30rpx;
	}


	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-right: 16rpx;
	}
</style>